// Copyright (c) 2009 Alistair Jones
// This program is made available under the terms of the MIT License.
package org.hypirinha.html.output.print;

import static org.hypirinha.html.AttributeFactory.*;
import static org.hypirinha.html.ElementFactory.*;
import org.hypirinha.html.elements.*;
import org.hypirinha.html.output.features.BasicEscaper;
import org.hypirinha.html.output.PrintAdapter;

import org.junit.Test;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;

public class EscapingTest {

    @Test
    public void shouldEscapeAttributesAndTextNodesSoThatDocumentStructureIsPreserved() {
        Title content = title(id("\"quoted attribute\""));
        content.text("< less than & greater than >");

        String output = new PrintAdapter().asString(content);

        Assert.assertEquals(MultilineString.lines(
                "<title id=\"&quot;quoted attribute&quot;\">&lt; less than &amp; greater than &gt;</title>"
                ), output);
    }
    
    @Test
    public void shouldOnlyEscapeQuotesInAttributeValuesAndNotInTextNodesWhereTheyArePermittedWithoutEscaping() {
        Title content = title(id("\"quoted attribute\""));
        content.text("these \"quotes\" will not be escaped");

        String output = new PrintAdapter().asString(content);

        Assert.assertEquals(MultilineString.lines(
                "<title id=\"&quot;quoted attribute&quot;\">these \"quotes\" will not be escaped</title>"
                ), output);
    }

    @Test
    public void shouldDelegateToCustomEscaperWhenSupplied() {
        Title content = title();
        content.text("Champs Elysées!");

        class AccentEscpaper extends BasicEscaper {
            public String escapeContent(String text) {
                return super.escapeContent(text).replaceAll("é", "&eacute;");
            }
        }
        String output = new PrintAdapter(new AccentEscpaper()).asString(content);

        Assert.assertEquals(MultilineString.lines(
                "<title>Champs Elys&eacute;es!</title>"
                ), output);
    }
}